<?php
namespace Api\Controller;
use Api\Model\OrderModel;
use Org\Util\SString;
use Api\Model\UserCustomerModel;
use Api\Model\OrderProjectModel;
use Api\Model\ProjectModel;
use Api\Model\TagModel;
use Api\Model\FileModel;
use Api\Model\OrderProjectFileModel;
use Api\Model\OrderProjectTagModel;
use Api\Model\OrderRebackModel;


/**
 * 工单控制器
 */
class OrderController extends ApiController{
    /**
     * @api {post} /Order/create_order 01创建订单信息
     * @apiDescription 获取我的客户列表
     * @apiGroup 03Order
     * @apiPermission token
     * @apiVersion 1.0.1
     * @apiParam {string}  customer_id 所属客户编号
     * @apiParam {string}  project_id 产品ID,多个产品使用英文半角逗号拼接
     * @apiParam {string}  project_count 产品数量,与ID一一对应,使用英文半角逗号拼接
     * @apiParam {number}  type 类型管理,1询价2订单 
     * @apiParam {string}  remark 订单备注
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "code": "0",
     *      "msg": "成功",
     *      "time": "2018-06-21 17:04:06",
     *      "data": {
     *      }
     *  }
     * @apiErrorExample Error-Response:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":2,
     *      "msg":"参数错误",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     * @apiErrorExample Error-Empty:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":16,
     *      "msg":"查无数据",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     */
    public function create_orderAction(){
        $post = I('post.');
        $project_id = explode(',', $post['project_id']);// 获取产品编号
        $customer_id = $post['customer_id'];// 获取客户编号
        $project_count = explode(',', $post['project_count']);// 获取购买数量
        $u_info = $this->check_token();
        if(empty($post['type']) || empty($project_id) || empty($customer_id)){
            return $this->returnCode(2);
        }
        // 创建一个已删除工单,获取工单ID
        $order = new OrderModel();
        $order_id = $order->create_info(['status'=>98]);// 创建一个删除的工单编号
        $post['order_no'] = C('ORDER_ID');
        preg_match('/%rand(\d)%/', $post['order_no'],$arr);
        if($arr[1]){
            $len = $arr[1];
            $rand = (new SString())->randString($len, 1);
            $post['order_no'] = date(preg_replace("/%rand(\d)%/", $rand, $post['order_no']));
        }
        preg_match('/%id(.*?)%/', $post['order_no'],$arr);
        if($arr[1]){
            $len = $arr[1];
            $rand = sprintf("%{$len}d",$order_id);
            $post['order_no'] = date(preg_replace("/%id(.*)%/", $rand, $post['order_no']));
        }
        $user_customer = (new UserCustomerModel())
                ->where([
                    'uid'=>$u_info['id'],
                    'ststus' => ['neq',98]
                ])
                ->get_info($customer_id);
        if(empty($user_customer)){
            return $this->returnCode(16);
        } else {
            $post['uid'] = $u_info['id'];
            $post['name'] = $user_customer['name'];
            $post['composer'] = $user_customer['company'];
            $post['phone'] = $user_customer['phone'];
        }
        $_order_project = new OrderProjectModel();
        $_project = new ProjectModel();
        $_order_project_file = new OrderProjectFileModel();
        $_order_project_tag = new OrderProjectTagModel();
        $_tag = new TagModel();
        $_file = new FileModel();
        $order_price = 0;
        foreach($project_id as $k => $v){
            $temp = $_project->get_info($v);
            unset($temp['id']);
            $temp['oid'] = $order_id;
            $temp['buy_count'] = $project_count[$k];
            $new_project_id = $_order_project->create_info($temp);
            $order_price += $temp['price'];
            $file_list = $_file->get_link()
                    ->where([
                        'target_name' => $_file->get_table_id('project'),
                        'target_id' => $v,
                        'status' => ['neq',98]
                    ])
                    ->select();
            foreach($file_list as $vv){
                $_order_project_file->create_info([
                    'p_id' => $new_project_id,
                    'fid' => $vv['file_id'],
                    'file_name' => $vv['file_name']
                ]);
            }
            $tag_list = $_tag->get_link()->where([
                'target_id' => $v,
                'target_name' => $_tag->get_table_id('project'),
                'status' => ['neq',98]
            ])->select();
            foreach($tag_list as $vv){
                $tag_info = $_tag->where(['status'=>['neq',98]])->get_info($vv['file_id']);
                $_order_project_tag->create_info([
                    'p_id' => $new_project_id,
                    'name' => $tag_info['name'],
                    'desc' => $tag_info['desc'],
                    'type' => $tag_info['type']
                ]);
            }
        }
        $post['md_time'] = NOW_TIME;
        $post['remark'] = $post['remark'];
        $post['price'] = $order_price;
        $post['ad_time'] = NOW_TIME;
        $post['status'] = 1;
        $order->where(['id'=>$order_id])->save($post);
        return $this->returnCode(0);// 提交订单
    }
    
    /**
     * @api {post} /Order/get_order 02获取我的订单列表
     * @apiDescription 获取我的订单列表
     * @apiGroup 03Order
     * @apiPermission token
     * @apiVersion 1.0.2
     * @apiParam {number}  p0 查询页数,默认1,表示第一页
     * @apiParam {number}  p1 查询条数,默认20,表示每页20条
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "code": 0,
     *      "msg": "成功",
     *      "time": "2018-06-25 10:03:39",
     *      "data": {
     *          "count": "1",// 查询条数
     *          "list": [// 查询到的列表
     *              {
     *                  "id": "4",// 订单所属编号
     *                  "order_no": "20180625-000004",// 订单号
     *                  "express_name": "顺丰快递",// 快递名称
     *                  "express_no": "821159129754",// 快递单号
     *                  "is_shouhuo": "2",// 是否已收货，1是2否
     *                  "customer": {// 订单所关联客户信息
     *                      "name": "测试分类",// 客户姓名
     *                      "company": "分析报告",// 客户所属公司
     *                      "phone": "14563453233"// 客户电话
     *                  },
     *                  "type": "1",// 类型,1询价2订单 
     *                  "remark": "",// 订单备注
     *                  "price": "246.00",// 订单价格
     *                  "md_time": "2018-06-25 09:35:42",// 下单时间
     *                  "zf_time": "",// 支付时间
     *                  "hd_time": "",// 支付确认时间[三方回调时间]
     *                  "zf_price": "",// 支付金额
     *                  "project": [// 订单包含产品列表
     *                      {
     *                          "name": "aaaa",// 产品名称
     *                          "price": "12.00",// 产品单价
     *                          "wl_no": "sdgbxc",// 物料编号
     *                          "content": "&lt;p&gt;adfdsgvgxcv修复你的观念&lt;/p&gt;\r\n",// 产品详情
     *                          "id": "1",// 订单产品编号，退单/维修时需要该编号
     *                          "buy_count": "1",// 购买数量
     *                          "file": [// 关联图片信息
     *                              "image/2018-06-11/2018-06-11/5b1dde927e4f2.jpg",
     *                              "image/2018-06-11/2018-06-11/5b1dde927c383.jpg",
     *                              "image/2018-06-11/2018-06-11/5b1dde9278bce.jpg"
     *                          ],
     *                          "anli": [// 关联案例名称列表
     *                              "奥术大师"
     *                          ],
     *                          "fenlei": [// 关联分类列表
     *                              "测试分类111"
     *                          ],
     *                          "pinpai": [// 关联品牌列表
     *                              "测试品牌"
     *                          ]
     *                      }
     *                  ]
     *              }
     *          ]
     *      }
     *  }
     * @apiSuccessExample Success-Empty:
     * HTTP/1.1 200 OK
     * {
     *      "code": 0,
     *      "msg": "成功",
     *      "time": "2018-06-25 10:03:39",
     *      "data": {
     *          "count": "0",
     *          "list": [
     *          ]
     *  }
     * @apiErrorExample Error-Response:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":2,
     *      "msg":"参数错误",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     * @apiErrorExample Error-Empty:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":16,
     *      "msg":"查无数据",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     * @apiErrorExample Error-User:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":21,
     *      "msg":"用户未登录",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     */
    public function get_orderAction(){
        $return_list = [];
        $_order = new OrderModel();
        $_order_project = new OrderProjectModel();
        $_order_project_file = new OrderProjectFileModel();
        $_order_project_tag = new OrderProjectTagModel();
        $_file = new FileModel();
        $u_info = $this->check_token();
        $p0 = I('post.p0',1,'intval');
        $p1 = I('post.p1',20,'intval');
        $p0 = ($p0 - 1) * $p1;
        $p0 < 0 && $p0 = 0;
        $list = $_order->where([
            'uid' => $u_info['id'],
        ])->getList($p0,$p1);// 获取全部订单信息
        $return_list['count'] = $_order->where(['uid' => $u_info['id']])->getCount();
        foreach($list as $v){
            $project = $_order_project
                    ->where([
                        'oid'=>$v['id'],
                        'status' => ['neq',98],
                    ])
                    ->field(['name','price','wl_no','content','id','buy_count'])
                    ->select();
            foreach($project as $k => $vv){
                $project[$k]['file'] = [];
                $project[$k]['anli'] = [];
                $project[$k]['fenlei'] = [];
                $project[$k]['pinpai'] = [];
                $temp = $_order_project_file->where(['p_id'=>$vv['id']])->getList(0,999,FALSE,'`id` DESC');
                foreach($temp as $kv){
                    $project[$k]['file'][] = $_file->get_info($kv['fid'])['file_path'];
                }
                $temp = $_order_project_tag->where(['p_id'=>$vv['id']])->select();
                foreach ($temp as $kv){
                    if($kv['type'] == get_config_id('TagType','案例')){
                        $project[$k]['anli'][] = $kv['name'];
                    }else if($kv['type'] == get_config_id('TagType','分类')){
                        $project[$k]['fenlei'][] = $kv['name'];
                    }else if($kv['type'] == get_config_id('TagType','品牌')){
                        $project[$k]['pinpai'][] = $kv['name'];
                    }
                }
            }
            $return_list['list'][] = [
                'id' => $v['id'],
                'order_no' => $v['order_no'],
                'express_name' => $v['kd_name'],
                'express_no' => $v['kd_no'],
                'is_shouhuo' => $v['is_shouhuo'],
                'customer' => [
                    'name' => $v['name'],
                    'company' => $v['composer'],
                    'phone' => $v['phone'],
                ],
                'type' => $v['type'],
                'remark' => $v['remark'],
                'price' => $v['price'],
                'md_time' => $v['md_time']?date('Y-m-d H:i:s',$v['md_time']):'',
                'zf_time' => $v['zf_time']?date('Y-m-d H:i:s',$v['zf_time']):'',
                'hd_time' => $v['hd_time']?date('Y-m-d H:i:s',$v['hd_time']):'',
                'zf_price' => $v['price_success'],
                'project' => $project,
            ];
        }
        return $this->returnCode($return_list);
    }
    
    /**
     * @api {post} /Order/project_reback 03退换货申请信息
     * @apiDescription 退换货申请信息
     * @apiGroup 03Order
     * @apiPermission token
     * @apiVersion 1.0.0
     * @apiParam {number}  order_id 订单编号
     * @apiParam {number}  order_project_id 订单关联的产品编号
     * @apiParam {string}  content 退单/维修原因
     * @apiParam {number}  type 退单种类，1退货  2换货  3维修[维修]
     * @apiParam {number}  reback 退单类型，1退货[单个产品，默认]，2退单[全部产品]
     * @apiParam {number}  reback_type 售后类型，1初次[默认]，2非初次
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "code": 0,
     *      "msg": "成功",
     *      "time": "2018-06-25 10:03:39",
     *      "data": {
     *      }
     *  }
     * @apiErrorExample Error-Response:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":2,
     *      "msg":"参数错误",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     * @apiErrorExample Error-Empty:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":16,
     *      "msg":"查无数据",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     * @apiErrorExample Error-Empty:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":20,
     *      "msg":"查无权限",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     * @apiErrorExample Error-User:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":21,
     *      "msg":"用户未登录",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     * @apiErrorExample Error-Order:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":25,
     *      "msg":"该订单不允许退款",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     */
    public function project_rebackAction(){
        $post = I('post.');
        $post['type'] || $post['type'] = 3;
        $post['reback'] || $post['reback'] = 1;
        $_order_reback = new OrderRebackModel();
        $_order_project = new OrderProjectModel();
        $_order = new OrderModel();
        $order_info = $_order->get_info($post['order_id']);
        if(empty($order_info)){
            return $this->returnCode(16);
        }
        $u_info = $this->check_token();
        if($order_info['uid'] != $u_info['id']){
            return $this->returnCode(20);// 如果是退订非本人工单则报错查无权限
        }
        if(!in_array($order_info['status'], $_order->get_status_reback())){
            return $this->returnCode(25);
        }
        if($post['reback_type'] == 2){
            if($post['reback'] == 2){
                // 退全部订单
                $project_info = $_order_project->where(['oid'=>$post['order_id']])->select();// 退整个订单
            } else {
                $project_info = $_order_project->where(['oid'=>$post['order_id'],'id'=>$post['order_project_id']])->select();// 每次只能退一件产品
                // 使用select查询，和退整个订单一样构成数据，方便做退单处理
            }
        } else {
            if($post['reback'] == 2){
                // 退全部订单
                $project_info = $_order_project->where(['oid'=>$post['order_id'],'status' => 99])->select();// 退整个订单
            } else {
                $project_info = $_order_project->where(['oid'=>$post['order_id'],'id'=>$post['order_project_id'],'status' => 99])->select();// 每次只能退一件产品
                // 使用select查询，和退整个订单一样构成数据，方便做退单处理
            }
        }
        if(empty($project_info)){
            return $this->returnCode(16);
        }
        // 插入退货列表
        foreach ($project_info as $v){
            $_order_reback->add([
                'order_id' => $v['oid'],
                'order_project_id' => $v['id'],
                'content' => $post['content'],
                'ad_time' => NOW_TIME,
                'status' => 1,
                'type' => $post['type'],
                'uid' => $u_info['id'],
            ]);
            $_order_project->where(['id'=>$v['id'],'status'=>99])->save(['status'=>98]);
        }
        return $this->returnCode(0);
    }
    
    /**
     * @api {post} /Order/reback_list 04我的售后列表
     * @apiDescription 我的售后列表
     * @apiGroup 03Order
     * @apiPermission token
     * @apiVersion 1.0.1
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "code": 0,
     *      "msg": "成功",
     *      "time": "2018-07-02 15:50:01",
     *      "data": {
     *          "count": "1",// 查询到的退单条数
     *          "list": [// 查询到的退单数据
     *              {
     *                  "project": {// 退单产品信息【如果是整体退单则分散成产品进行陈列】
     *                      "name": "测试分类111",// 产品名称
     *                      "price": "123.00",// 产品单价
     *                      "wl_no": "水电费",// 物料编号
     *                      "content": "&lt;p&gt;萨法VBV型&lt;/p&gt;\r\n",// 产品简介
     *                      "buy_count": "1",// 购买数量
     *                      "status": "有退单"// 状态信息
     *                      "reback": {// 退单信息展示
     *                          "reback_time": "2018-07-02 14:22:43",// 退单申请时间
     *                          "reback_type": "维修",// 退单类型
     *                          "_type": "维修",// 退单类型数字值
     *                          "reback_status": "已申请"// 退单状态
     *                          "_status": "1"// 退单状态数字值
     *                      }
     *                  },
     *                  "project_file": [// 产品图片列表
     *                      "image/2018-06-11/2018-06-11/5b1dde9278bce.jpg",
     *                      "image/2018-06-19/2018-06-19/5b28bda4ca3c8.jpg"
     *                  ],
     *                  "project_fenlei": [// 产品分类标签
     *                      "测试分类111"
     *                  ],
     *                  "project_pinpai": [// 产品品牌标签
     *                  ],
     *                  "order": {
     *                      "order_no": "20180625-000004",// 订单编号列表
     *                      "composer": {// 订单所属客户信息
     *                          "name": "测试分类",// 客户姓名
     *                          "composer": "分析报告",// 所在公司
     *                          "phone": "14563453233"// 客户电话
     *                      },
     *                      "type": "询价订单",// 订单类型
     *                      "md_time": "2018-06-25 09:35:42",// 购买时间
     *                      "remark": "",// 订单备注
     *                      "price": "246.00",// 订单金额
     *                      "status": "待支付"// 订单支付状态
     *                  }
     *              }
     *          ]
     *      }
     *  }
     * @apiSuccessExample Success-Empty:
     * HTTP/1.1 200 OK
     * {
     *      "code": 0,
     *      "msg": "成功",
     *      "time": "2018-06-25 10:03:39",
     *      "data": {
     *          "count": "0",
     *          "list": [
     *          ]
     *  }
     * @apiErrorExample Error-Empty:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":16,
     *      "msg":"查无数据",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     * @apiErrorExample Error-User:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":21,
     *      "msg":"用户未登录",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     */
    public function reback_listAction(){
        $u_info = $this->check_token();
        $_order_reback = new OrderRebackModel();
        $_order_project = new OrderProjectModel();
        $_order_project_tag = new OrderProjectTagModel();
        $_order_project_file = new OrderProjectFileModel();
        $_order = new OrderModel();
        $_file = new FileModel();
        // 获取退单列表
        $list = $_order_reback->where(['status'=>['neq',98],'uid'=>$u_info['id']])->select();
        $reback_list = ['count'=> count($list)];
        foreach($list as $v){
            $temp_project = $_order_project->get_info($v['order_project_id']);
            $temp_p_file = $_order_project_file->where(['p_id'=>$v['order_project_id']])->select();
            $project_file = [];
            foreach($temp_p_file as $vt){
                $temp = $_file->get_info($vt['fid']);
                $project_file[] = $temp['file_path'];
            }
            $project_fenlei = [];
            $temp_p_fenlei = $_order_project_tag->where(['p_id'=>$v['order_project_id'],'type'=> get_config_id('TagType', '分类')])->select();
            foreach($temp_p_fenlei as $vt){
                $project_fenlei[] = $vt['name'];
            }
            $project_pinpai = [];
            $temp_p_fenlei = $_order_project_tag->where(['p_id'=>$v['order_project_id'],'type'=> get_config_id('TagType', '品牌')])->select();
            foreach($temp_p_fenlei as $vt){
                $project_pinpai[] = $vt['name'];
            }
            $temp_order = $_order->get_info($v['order_id']);
            $reback_list['list'][] = [
                // 产品详情信息
                'project' => [
                    'name' => $temp_project['name'],
                    'price' => $temp_project['price'],
                    'wl_no' => $temp_project['wl_no'],
                    'content' => $temp_project['content'],
                    'buy_count' => $temp_project['buy_count'],
                    'status' => $temp_project['status']==99?'正常':'有退单',
                    'reback' => [
                        'reback_time' => date('Y-m-d H:i:s',$v['ad_time']),
                        'reback_type' => $_order_reback->get_config($v['type'],'type'),
                        '_type' => $v['type'],
                        'reback_status' => $_order_reback->get_config($v['status'],'status'),
                        '_status' => $v['status'],
                    ],
                ],
                'project_file' => $project_file,
                'project_fenlei' => $project_fenlei,
                'project_pinpai' => $project_pinpai,
                // 订单详情信息
                'order' => [
                    'order_no' => $temp_order['order_no'],
                    'composer' => [
                        'name' => $temp_order['name'],
                        'composer' => $temp_order['composer'],
                        'phone' => $temp_order['phone'],
                    ],
                    'type' => $temp_order['type'] == 1?'询价订单':'正常支付',
                    'md_time' => date('Y-m-d H:i:s',$temp_order['md_time']),
                    'remark' => $temp_order['remark'],
                    'price' => $temp_order['price'],
                    'status' => $_order->get_status($temp_order['status']),
                ],
            ];
        }
        return $this->returnCode($reback_list);
    }
    
    /**
     * @api {post} /Order/reback_list 05确认收货
     * @apiDescription 确认收货
     * @apiGroup 03Order
     * @apiPermission token
     * @apiVersion 1.0.0
     * @apiParam {number}  order_id 订单编号
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
     * {
     *      "code": 0,
     *      "msg": "成功",
     *      "time": "2018-07-02 15:50:01",
     *      "data": {
     *      }
     *  }
     * @apiErrorExample Error-Empty:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":16,
     *      "msg":"查无数据",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     * @apiErrorExample Error-User:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":21,
     *      "msg":"用户未登录",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     * @apiErrorExample Error-System:
     *  HTTP/1.1 200 OK
     *  {
     *      "code":1,
     *      "msg":"失败",
     *      "time":"2018-06-20 23:33:11",
     *      "data":{
     *      }
     *  }
     */
    public function take_overAction(){
        $post = I('post.');
        $_order = new OrderModel();
        $u_info = $this->check_token();
        $order_info = $_order->where([
            'uid' => $u_info['id'],
            'id' => $post['order_id']
        ])->find();
        if(empty($order_info)){
            return $this->returnCode(16);
        }
        if($_order->where([
            'uid' => $u_info['id'],
            'id' => $post['order_id']
        ])->save([
            'is_shouhuo' => 1,
            'shouhuo_time' => NOW_TIME
        ])){
            return $this->returnCode(0);
        }
        return $this->returnCode(1);
    }
}
